package com.cskaoyan.mall.promo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.promo.cache.CacheManager;
import com.cskaoyan.mall.promo.dto.*;
import com.cskaoyan.mall.promo.form.CreatePromoOrderRequest;
import com.cskaoyan.mall.promo.form.PromoProductDetailRequest;
import com.cskaoyan.mall.promo.service.PromoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Date;

@RestController
@RequestMapping("/shopping")
@Slf4j
public class PromoController {


    @Autowired
    PromoService promoService;



    @Autowired
    CacheManager cacheManager;



    @GetMapping("/seckilllist")
    public ResponseData getPromotionList(@NotNull @RequestParam Integer sessionId) {

        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        PromoInfoResponse promoInfoResponse = promoService.getPromoList(sessionId, yyyyMMdd);
        return new ResponseUtil<>().setData(promoInfoResponse);

    }


    @PostMapping("/promoProductDetail")
    public ResponseData getPromoItemDetail(@Validated @RequestBody PromoProductDetailRequest request) {

        PromoProductDetailDto promoProductProduct = promoService.getPromoProductDetail(request);
        return new ResponseUtil<>().setData(promoProductProduct);
    }


    @PostMapping("/seckill")
    public ResponseData seckill(HttpServletRequest request,
                                @Validated @RequestBody CreatePromoOrderRequest createPromoOrderRequest) {

        String userInfo = request.getHeader("user_info");
        JSONObject jsonObject = JSON.parseObject(userInfo);
        String username = (String) jsonObject.get("username");
        Integer uid = (Integer) jsonObject.get("uid");
        createPromoOrderRequest.setUserId(uid.longValue());
        createPromoOrderRequest.setUsername(username);

        promoService.createPromoOrderInTransaction(createPromoOrderRequest);
        return new ResponseUtil<>().setData(null);
    }


}
